package com.ewzj.bigdata.mvp.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ewzj.bigdata.R;
import com.ewzj.bigdata.app.constants.AppConstants;
import com.ewzj.bigdata.di.component.DaggerSearchComponent;
import com.ewzj.bigdata.di.module.SearchModule;
import com.ewzj.bigdata.mvp.contract.SearchContract;
import com.ewzj.bigdata.mvp.model.entity.resbean.SearchResult;
import com.ewzj.bigdata.mvp.model.entity.resbean.SearchResultBean;
import com.ewzj.bigdata.mvp.model.entity.resbean.SearchResultHot;
import com.ewzj.bigdata.mvp.model.entity.resbean.TabBean;
import com.ewzj.bigdata.mvp.presenter.SearchPresenter;
import com.ewzj.bigdata.mvp.ui.adapter.SearchAdapter;
import com.ewzj.bigdata.mvp.ui.adapter.SearchResultAdapter;
import com.ewzj.bigdata.mvp.ui.adapter.SearchResultHotAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.functions.Function;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class SearchActivity extends BaseActivity<SearchPresenter> implements SearchContract.View {

    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.flowlayout)
    TagFlowLayout flowlayout;
    @BindView(R.id.search_rv_result)
    RecyclerView searchRvResult;
    private List<SearchResultHot> mResults1;
    private SearchAdapter searchAdapter;
    List<TabBean> tabBeans;
    /**
     * 当前选中哪一个lab
     */
    private int select_index = 0;
    List<SearchResultBean> searchResultBeans;

    @Override
    public void setupActivityComponent(AppComponent appComponent) {
        DaggerSearchComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .searchModule(new SearchModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(Bundle savedInstanceState) {
        return R.layout.activity_search; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        tabBeans = getIntent().getParcelableArrayListExtra(AppConstants.EXTRA_DATA);
        if (tabBeans == null) {
            finish();
        }
        flowlayout.setAdapter(new TagAdapter<TabBean>(tabBeans) {
                                  @Override
                                  public View getView(FlowLayout parent, int position, TabBean tabBean) {
                                      TextView tv = (TextView) LayoutInflater.from(parent.getContext()).inflate(R.layout.tag_seach_item,
                                              flowlayout, false);
                                      tv.setText(tabBean.getName());
                                      return tv;
                                  }
                              }
        );
        flowlayout.getAdapter().setSelectedList(0);
        initEditSearch();
    }

    @Override
    protected void onResume() {
        super.onResume();

        mPresenter.loadHotSeach();
    }

    private void initEditSearch() {
        etContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId == EditorInfo.IME_ACTION_SEARCH)
                {
                    Set positions=flowlayout.getSelectedList();
                    String string=v.getText().toString();
                    TabBean tabBean=tabBeans.get((Integer) positions.toArray()[0]);
                    SearchResultBean searchResultBean=new SearchResultBean();
                    searchResultBean.setCategory_id(Integer.parseInt(tabBean.getId()));
                    searchResultBean.setKeywords(string);
                    if (TextUtils.isEmpty(string)){
                        ArmsUtils.snackbarText("搜索内容不能为空");
                    }else {
                        mPresenter.saveHisData(searchResultBean);
                        Intent intent=new Intent(SearchActivity.this,SearchResultActivity.class);
                        intent.putExtra(AppConstants.EXTRA_DATA,searchResultBean);
                        ArmsUtils.startActivity(intent);
                    }
                }
                return false;
            }
        });
    }


    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }


    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void showHotSearchData(List<SearchResultBean> hotsearchResultBeans) {
        String hisStr = DataHelper.getStringSF(this, AppConstants.APPHISTORY);
        Gson mGson = ArmsUtils.obtainAppComponentFromContext(this).gson();
        if (TextUtils.isEmpty(hisStr)) {
            searchResultBeans = new ArrayList<>();
        } else {
            searchResultBeans = mGson.fromJson(hisStr, new TypeToken<List<SearchResultBean>>() {

            }.getType());
        }
        if (!searchResultBeans.isEmpty()) {
            searchResultBeans.add(0, new SearchResultBean(0, "搜索记录", 0));
            searchResultBeans.add(new SearchResultBean(0, "热门搜索", 2));
            hotsearchResultBeans.addAll(0, searchResultBeans);
        } else {
            hotsearchResultBeans.add(0, new SearchResultBean(0, "热门搜索", 2));
        }
        ArmsUtils.configRecyclerView(searchRvResult,new LinearLayoutManager(this));
        searchAdapter=new SearchAdapter(hotsearchResultBeans);
        searchAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                SearchResultBean searchResultBean= (SearchResultBean) adapter.getData().get(position);
                if (searchResultBean.getType()==0||searchResultBean.getType()==2){
                    return;
                }
                Intent intent=new Intent(SearchActivity.this,SearchResultActivity.class);
                intent.putExtra(AppConstants.EXTRA_DATA,searchResultBean);
                ArmsUtils.startActivity(intent);
            }
        });
        searchRvResult.setAdapter(searchAdapter);

    }

    @Override
    public List<SearchResultBean> obtainResultsBean() {
        if (searchResultBeans==null){
            searchResultBeans=new ArrayList<>();
        }
        return searchResultBeans;
    }
}
